package com.example.demo.service.Impl;

import com.example.demo.entity.Event;
import com.example.demo.entity.User;
import com.example.demo.mapper.EventMapper;
import com.example.demo.service.EventService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Service
public class EventServiceImpl implements EventService {
    @Autowired
    EventMapper eventMapper;

    @Override
    public PageInfo<Event> list() {
        List<Event> events = eventMapper.list();
        PageInfo<Event> eventPageInfo = new PageInfo<>(events);
        return eventPageInfo;
    }

    @Override
    public PageInfo<Event> listByParams(Integer currentPage, Integer pageSize, String startDate, String endDate) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = null;
        Date date2 = null;
        if(startDate!=null){
            try {
                date1 = format.parse(startDate); // 解析为 Date 对象
            }catch (ParseException e) {
                System.err.println("Error parsing date: " + e.getMessage());
            }
        }
        if(endDate!=null){
            try {
                date2 = format.parse(endDate); // 解析为 Date 对象
            }catch (ParseException e) {
                System.err.println("Error parsing date: " + e.getMessage());
            }
        }
        PageHelper.startPage(currentPage,pageSize);
        List<Event> events = eventMapper.listByParams(date1,date2);
        events.sort(Comparator.comparing(Event::getUrgency).reversed());
        PageInfo<Event> eventPageInfo = new PageInfo<>(events);
        return eventPageInfo;
    }

    @Override
    public int addEvent(Event event, HttpSession session){
        Date now = new Date();
        event.setCreate_time(now);
        User user = (User) session.getAttribute("user");
        if(user != null){
            event.setUser_id(user.getId());
        }
        return eventMapper.add(event);
    }

    @Override
    public boolean changeEvent(Event event) {
        return eventMapper.changeEvent(event);
    }

    @Override
    public Event getEventById(Integer id) {
        return eventMapper.getEventById(id);
    }

    @Override
    public boolean deleteEventById(Integer id) {
        return eventMapper.deleteById(id);
    }

    @Override
    public void updateStatus(Integer id) {
        eventMapper.updateStatus(id);
    }
}
